package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServcieImpl implements ApBehaviorServcie {
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 查询文章行为数据
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询用户
        ApUser user = AppThreadUtil.getUser();
        if (user == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        boolean isLike=false,isUnlike=false,isCollection=false,isFollow=false;

        //1，查询收藏行为
        String collection_hash_key="USER_COLLECTION_"+dto.getArticleId();
        isCollection=redisTemplate.opsForHash().hasKey(collection_hash_key,user.getId()+"");
        //2.查询点赞行为
        String like_hash_key = "USER_LIKES_" + dto.getArticleId();
        isLike = redisTemplate.opsForHash().hasKey(like_hash_key, user.getId()+"");


        //3.查询关注行为
        String follow_hash_key = "USER_FOLLOW_" + user.getId();
        isFollow = redisTemplate.opsForHash().hasKey(follow_hash_key, dto.getAuthorId()+"");


        //4.查询不喜欢行为
        String unlike_hash_key = "USER_UNLIKES_" + dto.getArticleId();
        isUnlike = redisTemplate.opsForHash().hasKey(unlike_hash_key, user.getId()+"");

        //5.结果返回
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("isfollow", isFollow);
        resultMap.put("islike", isLike);
        resultMap.put("isunlike", isUnlike);
        resultMap.put("iscollection", isCollection);

        return ResponseResult.okResult(resultMap);
    }
}
